package com.smartthinking.dive;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper{

	private static final String DATABASE_NAME = "Squenda.db";
	  private static final int DATABASE_VERSION = 1;
	private String DATABASE_PATH = "/data/data/com.smartthinking.dive/databases/";
	  
	  private final Context mContext;
//	  private boolean mUpgradeDatabase = false;
//	  private boolean mCreateDatabase = false;
	  

	  public DatabaseHelper(Context context) {
		  super(context, DATABASE_NAME, null, DATABASE_VERSION);
		  mContext = context;
	  }
	  
	  public void initializeDatabase(String path) {
	      DATABASE_PATH = path;
	      getWritableDatabase();

	      mContext.deleteDatabase(DATABASE_NAME);
	      try {
	    	  Log.d(null,"copy DB to: "+ path );
	          copyDatabase();
	      } catch (IOException e) {
	    	  throw new Error("Error copying database");
	      }
	  }
	  
	  private void copyDatabase() throws IOException {
	      close();

	      InputStream input = mContext.getAssets().open(DATABASE_NAME);

	      String outFileName = DATABASE_PATH + DATABASE_NAME;

	      OutputStream output = new FileOutputStream(outFileName);

	      // Transfer bytes from the input file to the output file
	      byte[] buffer = new byte[1024];
	      int length;
	      while ((length = input.read(buffer)) > 0) {
	          output.write(buffer, 0, length);
	      }

	      output.flush();
	      output.close();
	      input.close();

	      getWritableDatabase().close();
	  }
	  

	  // Method is called during creation of the database
	  @Override
	  public void onCreate(SQLiteDatabase database) {
		  DatabaseTables.onCreate(database);
	  }

	  // Method is called during an upgrade of the database,
	  // e.g. if you increase the database version
	  @Override
	  public void onUpgrade(SQLiteDatabase database, int oldVersion,int newVersion) {
		  DatabaseTables.onUpgrade(database, oldVersion, newVersion);
	  }
	
}
